package cn.fl.product.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysCdMapApiService;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.condition.SysCdMapDQueryCondition;
import cmm.comm.facade.framework.dto.SysCdMapDDTO;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.product.service.IMfrInfoService;
import cn.fl.product.service.IPrdBscInfoService;
import cn.fl.product.transform.PrdBscInfoVOTransform;
import cn.fl.product.verify.VerifyMfr;
import cn.fl.product.vo.MfrInfoVO;
import cn.fl.product.vo.PrdBscInfoVO;
import cn.fl.product.vo.PrdCarInfoVO;
import cn.fl.product.vo.PrdImportInfoVO;
import cn.fl.system.transform.SysCdMapDVOTransform;
import cn.fl.system.vo.SysCdMapDVO;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import cn.lb.framework.poi.excel.entity.result.ExcelImportResult;
import cn.lb.framework.poi.excel.export.styler.ExcelExportStylerBorderImpl;

import com.alibaba.fastjson.JSON;

import fl.flow.facade.flow.constant.FlowConstant;
import fl.product.facade.product.api.IProductApiService;
import fl.product.facade.product.condition.PrdBscInfoQueryCondition;
import fl.product.facade.product.constant.ProductConstant;
import fl.product.facade.product.dto.PrdBscInfoDTO;
import fl.spl.facade.mfr.condition.MfrInfoQueryCondition;

/**
 * @Description: 产品基础信息表 客户端服务层接口实现
 * @Description: 持久层方法名称前缀：新增：insert* 删除：delete* 修改：update* 批量：batch* 查询对象：select* get* find* 查询集合：select*
 */
@Service
public class PrdBscInfoServiceImpl implements IPrdBscInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(PrdBscInfoServiceImpl.class);
	
	/**
	 * 产品 API 暴露服务
	 */
	@Autowired
	private IProductApiService productApiService;
	
	/**
	 * 映射表API服务
	 */
	@Autowired
	private ISysCdMapApiService sysCdMapApiService;
	
	/**
	 * 本地厂商服务
	 */
	@Autowired
	private IMfrInfoService prdMfrInfoService;
	
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 本地用户服务
	 */
//	@Autowired
//	private ISysUsrService sysUsrService;
	
	/**
	 * 用户服务API
	 */
	@Autowired
	private ISysUsrApiService sysUsrApiService;
	
	@Override
	public PrdBscInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "根据主键查询产品信息失败,主键参数为空.ID:"+id,CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		PrdBscInfoDTO dto = this.productApiService.selectPrdBscInfoById(id, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		PrdBscInfoVO prdBscInfoVO = PrdBscInfoVOTransform.toVO(dto);
		//金额处理
		if(null!=prdBscInfoVO){
			if(null!=prdBscInfoVO.getGuidePc()){
				prdBscInfoVO.setGuidePcDouble(DecimalUtils.convertFenToYuan(prdBscInfoVO.getGuidePc()));
			}
		}
		return prdBscInfoVO;
	}

	@Override
	public Long add(PrdBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增产品失败,产品对象参数为空.DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.addPrdBscInfo(PrdBscInfoVOTransform.toDTO(entity),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id))return false;
		//return this.prdBscInfoApiService.removeById(id);
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除产品失败,主键参数为空.IDS:"+com.alibaba.fastjson.JSONObject.toJSONString(ids),CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.removePrdBscInfoByIds(ids);
    }

	@Override
	public boolean modify(PrdBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改产品失败,产品对象参数为空.DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity),CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.modifyPrdBscInfo(PrdBscInfoVOTransform.toDTO(entity));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		
		//设置初始查看权限条件prdTypCdList
		List<String> prdTypCdList = this.getPrdTypCdListForInitList();
		if(CollectionUtils.isEmpty(prdTypCdList)){
			return page;
		}
		PrdBscInfoQueryCondition condition = (PrdBscInfoQueryCondition) page.getCondition();
		condition.setPrdTypCdList(prdTypCdList);
		page.setCondition(condition);
		
		page = this.productApiService.searchPrdBscInfoListPage(page, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		List<PrdBscInfoDTO> resultList = (List<PrdBscInfoDTO>) page.getResultList();
		List<PrdBscInfoVO> voList = PrdBscInfoVOTransform.toVOList(resultList);
		/*if(CollectionUtils.isNotEmpty(voList)){
			List<Long> crtUsrIdList = new ArrayList<Long>();
			for (PrdBscInfoVO prdBscInfoVO : voList) {
				if(StringUtils.isNotEmpty(prdBscInfoVO.getCrtUsrId())){
					crtUsrIdList.add(prdBscInfoVO.getCrtUsrId());
				}
				//设置提报人姓名
				Long crtUsrId = prdBscInfoVO.getCrtUsrId();
				if(null!=crtUsrId){
					SysUsrVO sysUsrVO = this.sysUsrService.selectById(crtUsrId, CurrentThreadContext.getCurrentSysCd());
					if(null!=sysUsrVO){
						prdBscInfoVO.setCrtUsrNm(sysUsrVO.getUsrNm());
					}
				}
			}
			
			if(CollectionUtils.isNotEmpty(crtUsrIdList)){
				SysUsrQueryCondition suQC = new SysUsrQueryCondition();
				suQC.setUsrIds(crtUsrIdList);
				List<SysUsrDTO> sysUsrList = this.sysUsrApiService.searchSysUsrList(suQC);
				if(CollectionUtils.isNotEmpty(sysUsrList)){
					for (PrdBscInfoVO prdBscInfoVO : voList) {
						for (SysUsrDTO sysUsrDTO : sysUsrList) {
							if(StringUtils.isNotEmpty(prdBscInfoVO.getCrtUsrId()) && prdBscInfoVO.getCrtUsrId().equals(sysUsrDTO.getId())){
								prdBscInfoVO.setCrtUsrNm(sysUsrDTO.getRefRlNm());
								break;
							}
						}
					}
				}
			}
		}*/
		//加入是否需要审核字段
		if(CollectionUtils.isNotEmpty(voList)){
			for (PrdBscInfoVO prdBscInfoVO : voList) {
				String prdTypCd = prdBscInfoVO.getPrdTypCd();
				SysDictionaryDTO sysDictionaryDTO = this.sysDictionaryApiService.getCode(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYE_CD, prdTypCd);
				if(null!=sysDictionaryDTO && ProductConstant.PRD_TYP_ATTR_1.equals(sysDictionaryDTO.getCodeAttr1())){
					prdBscInfoVO.setIsAudStsCd(ProductConstant.PRD_TYP_ATTR_1);
				}
			}
		}
		
		page.setResultList(voList);
		return page;
	}

	@Override
	public boolean enAblePrdBscInfo(Long id) throws BaseException {
		if(null == id){
			BaseLogUtils.info(logger, "enAblePrdBscInfo", "启用产品失败,主键参数为空.ID:"+id,CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.enAblePrdBscInfo(id, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
	}

	@Override
	public boolean disAblePrdBscInfo(Long id) throws BaseException {
		if(null == id){
			BaseLogUtils.info(logger, "disAblePrdBscInfo", "禁用产品失败,主键参数为空.ID:"+id,CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.disAblePrdBscInfo(id, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
	}
	
	@Override
	public JSONArray searchPrdTyeList() throws BaseException {
		//当前登录人所属组织架构配置的产品特征分类
		List<SysDictionaryDTO> prdTagSortList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYP_CATEGORY);
		List<String> finalPrdTagSortList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(prdTagSortList)){
			for (SysDictionaryDTO sysDictionaryDTO : prdTagSortList) {
				if(!finalPrdTagSortList.contains(sysDictionaryDTO.getCode())){
					finalPrdTagSortList.add(sysDictionaryDTO.getCode());
				}
			}
		}
		//所有产品类型
		List<SysDictionaryDTO> prdTyCdList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYE_CD);
		
		//根据产品特征分类过滤产品类型(产品类型代码属性2配置的是此产品类型对应的产品特征分类)
		List<SysDictionaryDTO> finalPrdTypCdList = prdTyCdList;
		if(CollectionUtils.isNotEmpty(prdTyCdList) && CollectionUtils.isNotEmpty(finalPrdTagSortList)){
			for (SysDictionaryDTO sysDictionaryDTO : prdTyCdList) {
				if(!finalPrdTagSortList.contains(sysDictionaryDTO.getCodeAttr2())){
					finalPrdTypCdList.remove(sysDictionaryDTO);
				}
			}
		}
		JSONArray array = this.getPrdTypCdTree(finalPrdTypCdList, ProductConstant.PRD_GEN_CD);
		
		
/*		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd("M0001");	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		//qc.setCodeGrpCd("PRD9999");//代码组值
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		JSONArray array = this.getMenuTree(searchSysCdMapDWithTargetList, ProductConstant.PRD_GEN_CD);
*/		
		return array;
	}
	/**
	 * TODO 2017-2-15
	 * 获取产品类型树
	 */
	private JSONArray getPrdTypCdTree(List<SysDictionaryDTO> list, String pidCode){
		JSONArray tree = new JSONArray();
		
		for (SysDictionaryDTO sysDictionaryDTO : list) {
			JSONObject obj = new JSONObject();
			obj.put("codeGrpCd", sysDictionaryDTO.getCode());//类型代码组值
			obj.put("code", sysDictionaryDTO.getCode());//类型代码
			obj.put("codeNm", sysDictionaryDTO.getCodeNm());//类型名称
			obj.put("codeAttr2", sysDictionaryDTO.getCodeAttr2());//产品特征分类
			String pCode = sysDictionaryDTO.getPCode();
			String code = sysDictionaryDTO.getCode();
			if(pidCode.equals(pCode)){
				JSONArray childTree = this.getPrdTypCdTree(list, code);
				if(childTree.size()==0){
					obj.put("children", null);
					tree.add(obj);
				}else{
					obj.put("children", childTree);
					tree.add(obj);
				}
			}
		}
		return tree;
	}

	
	@Override
	public JSONArray searchPrdTyeListForSearch() throws BaseException {
		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd(ProductConstant.SYS_MAP_M_TYP_CD_PRD_TYP_CD);	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		//qc.setCodeGrpCd("PRD9999");//代码组值
		//当前登录人所属组织架构配置的产品特征分类
		List<SysDictionaryDTO> prdTagSortList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYP_CATEGORY);
		List<String> finalPrdTagSortList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(prdTagSortList)){
			for (SysDictionaryDTO sysDictionaryDTO : prdTagSortList) {
				if(!finalPrdTagSortList.contains(sysDictionaryDTO.getCode())){
					finalPrdTagSortList.add(sysDictionaryDTO.getCode());
				}
			}
		}
		qc.setsCodeList(finalPrdTagSortList);
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		JSONArray array = this.getMenuTree(searchSysCdMapDWithTargetList, ProductConstant.PRD_GEN_CD);
		
		return array;
	}
	
	@Override
	public List<String> getPrdTypCdListForInitList() throws BaseException {
		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd(ProductConstant.SYS_MAP_M_TYP_CD_PRD_TYP_CD);	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		//当前登录人所属组织架构配置的产品特征分类
		List<SysDictionaryDTO> prdTagSortList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYP_CATEGORY);
		List<String> finalPrdTagSortList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(prdTagSortList)){
			for (SysDictionaryDTO sysDictionaryDTO : prdTagSortList) {
				if(!finalPrdTagSortList.contains(sysDictionaryDTO.getCode())){
					finalPrdTagSortList.add(sysDictionaryDTO.getCode());
				}
			}
		}
		qc.setsCodeList(finalPrdTagSortList);
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		List<String> pedTypCdList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(searchSysCdMapDWithTargetList)){
			for (SysCdMapDDTO sysCdMapDDTO : searchSysCdMapDWithTargetList) {
				pedTypCdList.add(sysCdMapDDTO.getTCode());
			}
		}
		return pedTypCdList;
	}

	@Override
	public List<SysCdMapDVO> searchSysCdMapDList(SysCdMapDQueryCondition condition) throws BaseException {
		List<SysCdMapDDTO> listDTO = this.sysCdMapApiService.searchSysCdMapDWithTargetList(condition);
		return SysCdMapDVOTransform.toVOList(listDTO);
	}
	
	@Override
	public List<PrdBscInfoVO> searchcarTypSelectByCon(String condition) throws BaseException {
		List<PrdBscInfoDTO> listDTO = this.productApiService.selectPrdSeriesList(condition);
		return PrdBscInfoVOTransform.toVOList(listDTO);
	}
	
	/**
	 * 获取产品类型树JSON
	 * @param list
	 * @param pidCode
	 * @return
	 */
	private JSONArray getMenuTree(List<SysCdMapDDTO> list, String pidCode){
		JSONArray tree = new JSONArray();
		for (SysCdMapDDTO sysCdMapDDTO : list) {
			JSONObject obj = new JSONObject();
			String code = sysCdMapDDTO.getTCode();
			obj.put("sGrpCd", sysCdMapDDTO.getSGrpCd());	//源代码组值
			obj.put("sCode", sysCdMapDDTO.getSCode());		//源代码值
			obj.put("tGrpCd", sysCdMapDDTO.getTGrpCd());	//目标代码组值
			obj.put("tCode", sysCdMapDDTO.getTCode());		//目标代码值
			obj.put("tName", sysCdMapDDTO.getTCodeNm());		//目标代码名
			String pid = sysCdMapDDTO.getTPCode();
			if(pidCode.equals(pid)){
				JSONArray childTree = this.getMenuTree(list, code);
				if(childTree.size()==0){
					obj.put("children", null);
					tree.add(obj);
				}else{
					obj.put("children", childTree);
					tree.add(obj);
				}
			}
		}
		return tree;
	}

	/*@Override
	public List<KeyValueVO> searchBrandList() throws BaseException {
		return this.getKvList(DictionaryConstant.CODE_PRD_BR_CD);
	}*/

	@Override
	public List<KeyValueVO> searchMfrKVList() throws BaseException {
		MfrInfoQueryCondition qc = new MfrInfoQueryCondition();
		qc.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_PASS);
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		List<MfrInfoVO> prdMfrInfoVOList = this.prdMfrInfoService.searchList(qc);
		List<KeyValueVO> kvList = new ArrayList<KeyValueVO>();
		if(CollectionUtils.isNotEmpty(prdMfrInfoVOList)){
			for (MfrInfoVO prdMfrInfoVO : prdMfrInfoVOList) {
				KeyValueVO kv = new KeyValueVO();
				kv.setKey(String.valueOf(prdMfrInfoVO.getId()));//厂商id
				kv.setValue(prdMfrInfoVO.getMfrName());//厂商名称
				kvList.add(kv);
			}
		}
		return kvList;
	}

	@Override
	public List<KeyValueVO> searchAudStsCdList() throws BaseException {
		return this.getKvList(DictionaryConstant.CODE_AUD_STS_CD);
	}
	
	@Override
	public List<KeyValueVO> searchBrCdListByUser() throws BaseException {
		List<KeyValueVO> result=new ArrayList<KeyValueVO>();
		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd(ProductConstant.SYS_MAP_M_TYP_CD_BR_CD);	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		//当前登录人所属组织架构配置的产品特征分类
		List<SysDictionaryDTO> prdTagSortList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYP_CATEGORY);
		List<String> finalPrdTagSortList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(prdTagSortList)){
			for (SysDictionaryDTO sysDictionaryDTO : prdTagSortList) {
				if(!finalPrdTagSortList.contains(sysDictionaryDTO.getCode())){
					finalPrdTagSortList.add(sysDictionaryDTO.getCode());
				}
			}
		}
		qc.setsCodeList(finalPrdTagSortList);
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		List<String> temp=new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(searchSysCdMapDWithTargetList)){
			for(SysCdMapDDTO sysCdMapDDTO : searchSysCdMapDWithTargetList){
				if(!temp.contains(sysCdMapDDTO.getTCode())){
					temp.add(sysCdMapDDTO.getTCode());
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysCdMapDDTO.getTCode());
					keyValueVO.setValue(sysCdMapDDTO.getTCodeNm());
					result.add(keyValueVO);
				}
			}
		}
		return result;
	}
	@Override
	public List<KeyValueVO> searchbizModCdListByUser(String bizTypCd) throws BaseException {
		List<KeyValueVO> result=new ArrayList<KeyValueVO>();
		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd(ProductConstant.SYS_MAP_M_TYP_MOD_CD);	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		List<String> finalList = new ArrayList<String>();
		finalList.add(bizTypCd);
		qc.setsCodeList(finalList);
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		List<String> temp=new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(searchSysCdMapDWithTargetList)){
			for(SysCdMapDDTO sysCdMapDDTO : searchSysCdMapDWithTargetList){
				if(!temp.contains(sysCdMapDDTO.getTCode())){
					temp.add(sysCdMapDDTO.getTCode());
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysCdMapDDTO.getTCode());
					keyValueVO.setValue(sysCdMapDDTO.getTCodeNm());
					result.add(keyValueVO);
				}
			}
		}
		return result;
	}
	@Override
	public List<KeyValueVO> searchprjTypCdListByUser(String bizTypCd) throws BaseException {
		List<KeyValueVO> result=new ArrayList<KeyValueVO>();
		SysCdMapDQueryCondition qc = new SysCdMapDQueryCondition();
		qc.setmTypCd(ProductConstant.SYS_MAP_M_TYP_PRJ_CD);	//映射类型代码
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());	//系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());	//组织架构代码
		List<String> finalList = new ArrayList<String>();
		finalList.add(bizTypCd);
		qc.setsCodeList(finalList);
		
		List<SysCdMapDDTO> searchSysCdMapDWithTargetList = this.sysCdMapApiService.searchSysCdMapDWithTargetList(qc);
		List<String> temp=new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(searchSysCdMapDWithTargetList)){
			for(SysCdMapDDTO sysCdMapDDTO : searchSysCdMapDWithTargetList){
				if(!temp.contains(sysCdMapDDTO.getTCode())){
					temp.add(sysCdMapDDTO.getTCode());
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysCdMapDDTO.getTCode());
					keyValueVO.setValue(sysCdMapDDTO.getTCodeNm());
					result.add(keyValueVO);
				}
			}
		}
		return result;
	}
	
	
	@Override
	public List<KeyValueVO> searchAudStsCdList1() throws BaseException {
		List<KeyValueVO> searchAudStsCdList = this.getKvList(DictionaryConstant.CODE_AUD_STS_CD);
		//过滤掉待提交 和 审核中
		List<KeyValueVO> searchAudStsCdListNew = new ArrayList<KeyValueVO>();
		if(CollectionUtils.isNotEmpty(searchAudStsCdList)){
			for (KeyValueVO keyValueVO : searchAudStsCdList) {
				if(!FlowConstant.FLOW_CHECK_STATE_NON.equals(keyValueVO.getKey())
						&& !FlowConstant.FLOW_CHECK_STATE_IN.equals(keyValueVO.getKey())
						&& !FlowConstant.FLOW_CHECK_STATE_REJECT.equals(keyValueVO.getKey())){
					searchAudStsCdListNew.add(keyValueVO);
				}
			}
		}
		return searchAudStsCdListNew;
	}

	/**
	 * Batch Add Product
	 */
	@Override
	public PrdImportInfoVO batchAddPrd(String filePath) throws BaseException {
		PrdImportInfoVO importInfoVO = new PrdImportInfoVO();
		//Excel-->PrdBscVOList
		PrdImportInfoVO verifyPrdInfo = this.getImportProductInfo(filePath);
		if(verifyPrdInfo.getVerifyFlag().equals(BaseConstant.IS_YESNO_YES)){
			List<PrdBscInfoVO> importProductInfoList = verifyPrdInfo.getPrdBscInfoVOList();
			if(CollectionUtils.isEmpty(importProductInfoList)){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "导入产品为空,请填写产品信息重新导入！");
			}
			//Batch Add Product
			List<PrdBscInfoDTO> addErrorList = this.productApiService.batchAddPrdBscInfo(PrdBscInfoVOTransform.toDTOList(importProductInfoList),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			int successSum = importProductInfoList.size() - addErrorList.size();
			int errorSum = addErrorList.size();
			//导出错误数据excel
			if(CollectionUtils.isNotEmpty(addErrorList)){
				String exportErrorDataExcelPath = this.exportErrorDataExcel(PrdBscInfoVOTransform.toVOList(addErrorList)); 
				importInfoVO.setDownFilePath(exportErrorDataExcelPath);
				importInfoVO.setFlag(0);
				String msg = successSum + "条添加成功,"+ errorSum +"条添加失败.请下载错误信息查看.";
				importInfoVO.setMassage(msg);
			}else{
				String msg = successSum + "条添加成功,"+ errorSum +"条添加失败.";
				importInfoVO.setMassage(msg);
				importInfoVO.setFlag(1);
			}
			importInfoVO.setDownFileName("BatchAddFaiedInfo.xlsx");
			return importInfoVO;
		}else{
			return verifyPrdInfo;
		}
	}
	
	//************************************私有方法************************************//
	
	/**
	 * 解析 Excel数据 --> java对象 : VOList
	 * @return
	 */
	private PrdImportInfoVO getImportProductInfo(String filePath) throws BaseException{
		PrdImportInfoVO importInfoVO = new PrdImportInfoVO();
		ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题占用行数
        params.setHeadRows(1);//表头占用行数
        params.setNeedSave(false);//是否保存文件
        params.setVerifyHanlder(new VerifyMfr(this.searchMfrKVList()));
        
        File file = new File(filePath);
        
        ExcelImportResult<Object> result = ExcelImportUtil.importExcelVerify(file, PrdBscInfoVO.class, params);
        if(!result.isVerfiyFail()){//验证成功
            List<Object> list = result.getList();
            //遍历 
            List<PrdBscInfoVO> prdList = new ArrayList<PrdBscInfoVO>();
            for (Object object : list) {
            	PrdBscInfoVO prdPrdBscInfoVO = (PrdBscInfoVO) object;
            	prdList.add(prdPrdBscInfoVO);
			}
            List<PrdBscInfoVO> prdVOList = this.convertPrdBscInfoVO(prdList);//转换字段
            importInfoVO.setVerifyFlag(1);
            importInfoVO.setPrdBscInfoVOList(prdVOList);
            
        }else{
            System.out.println("校验失败,出错信息:"+JSON.toJSONString(result.getErrorMsg()));
            Workbook book=result.getWorkbook();
            FileOutputStream fos = null;
            try {
            	//错误excel存放路径
            	String path = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH) + ProductConstant.PRD_VERIFY_SAVE_DIR;
        		path = path + System.currentTimeMillis() + (result.isXSSFWorkbook() == true ? ".xlsx" : ".xls");
                fos = new FileOutputStream(path);
                book.write(fos);
                importInfoVO.setVerifyFlag(0);
                importInfoVO.setMassage("产品导入表格中存在不合法数据,请下载错误信息查看");
                importInfoVO.setDownFilePath(path);
                importInfoVO.setDownFileName("PrdVerifyFaiedInfo"+(result.isXSSFWorkbook() == true ? ".xlsx" : ".xls"));
                //importInfoVO.setDownFilePath(SysUlFilesRecConstant.SYS_FILE_UPLOAD_Server_PATH + path);
            } catch (FileNotFoundException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
            } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
            }
            IOUtils.closeQuietly(fos);
        }
        return importInfoVO;
	}
	
	/**
	 * 转换字段(XXCdNm --> XXCd)
	 * 1.卡车
	 * 2.客车
	 * 3.乘用车 prdTypCdNm(类型) brCdNm(品牌) prdCyCdNm(国别) drvTypCdNm(驱动) grboxTypCdNm(变速箱类型) seatQtyCdNm(座位)
	 *         carStrcCdNm(车身结构) prdWayCdNm(生产方式)
	 * @param list
	 * @return
	 */
	private List<PrdBscInfoVO> convertPrdBscInfoVO(List<PrdBscInfoVO> list) throws BaseException {
		for (PrdBscInfoVO prdBscInfoVO : list) {
			//********************************基本信息需转换字段**********************************/
			//BSC_1.产品代码    分别维护
			//BSC_2.产品类型  
			List<KeyValueVO> kvList = this.getKvList(DictionaryConstant.CODE_PRD_TYE_CD);
			for (KeyValueVO kv : kvList) {
				String prdTypCdNm = prdBscInfoVO.getPrdTypCdNm();
				if(kv.getValue().equals(prdTypCdNm)){
					prdBscInfoVO.setPrdTypCd(kv.getKey());
				}
			}
			//BSC_3.产品品牌
			/*List<KeyValueVO> searchBrandList = this.getKvList(DictionaryConstant.CODE_PRD_BR_CD);
			for (KeyValueVO kv : searchBrandList) {
				if(kv.getValue().equals(prdBscInfoVO.getBrCdNm())){
					prdBscInfoVO.setBrCd(kv.getKey());
				}
			}*/
			
			//********************************乘用车信息需转换字段**********************************/
			PrdCarInfoVO prdCarInfoVO = prdBscInfoVO.getPrdCarInfoVO();
			if(null!=prdCarInfoVO){
				//CAR_0.产品代码
				prdBscInfoVO.setPrdCd(prdBscInfoVO.getPrdTypCd());
				//CAR_1.国别
				List<KeyValueVO> cyCdList = this.getKvList(DictionaryConstant.CODE_PRD_CY_CD);
				for (KeyValueVO kv : cyCdList) {
					String prdCyCdNm = prdCarInfoVO.getPrdCyCdNm();
					if(kv.getValue().equals(prdCyCdNm)){
						prdCarInfoVO.setPrdCyCd(kv.getKey());
					}
				}
				//CAR_2.驱动
				List<KeyValueVO> drvTypCdList = this.getKvList(DictionaryConstant.CODE_PRD_DRV_TYP_CD);
				for (KeyValueVO kv : drvTypCdList) {
					String prdDrvTypCdNm = prdCarInfoVO.getDrvTypCdNm();
					if(kv.getValue().equals(prdDrvTypCdNm)){
						prdCarInfoVO.setDrvTypCd(kv.getKey());
					}
				}
				//CAR_3.变速箱类型
				List<KeyValueVO> grboxTyCdList = this.getKvList(DictionaryConstant.CODE_PRD_GRBOX_TYP_CD);
				for (KeyValueVO kv : grboxTyCdList) {
					String grboxTypCdNm = prdCarInfoVO.getGrboxTypCdNm();
					if(kv.getValue().equals(grboxTypCdNm)){
						prdCarInfoVO.setGrboxTypCd(kv.getKey());
					}
				}
				//CAR_4.座位
				List<KeyValueVO> seatQtyCd = this.getKvList(DictionaryConstant.CODE_PRD_SEAT_QTY_CD);
				for (KeyValueVO kv : seatQtyCd) {
					String seatQtyCdNm = prdCarInfoVO.getSeatQtyCdNm();
					if(kv.getValue().equals(seatQtyCdNm)){
						prdCarInfoVO.setSeatQtyCd(kv.getKey());
					}
				}
				//CAR_5.车身结构
				List<KeyValueVO> carStrcCdList = this.getKvList(DictionaryConstant.CODE_PRD_CAR_STRC_CD);
				for (KeyValueVO kv : carStrcCdList) {
					String carStrcCdNm = prdCarInfoVO.getCarStrcCdNm();
					if(kv.getValue().equals(carStrcCdNm)){
						prdCarInfoVO.setCarStrcCd(kv.getKey());
					}
				}
				//CAR_6.生产方式
				List<KeyValueVO> wayCdList = this.getKvList(DictionaryConstant.CODE_PRD_WAY_CD);
				for (KeyValueVO kv : wayCdList) {
					String prdWayCdNm = prdCarInfoVO.getPrdWayCdNm();
					if(kv.getValue().equals(prdWayCdNm)){
						prdCarInfoVO.setPrdWayCd(kv.getKey());
					}
				}
			}
			
			//设置创建人 创建时间
			prdBscInfoVO.setCrtTm(new Date());
			prdBscInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			
			//设置厂商ID
			//查询所有厂商进行匹配 
			/*List<KeyValueVO> mfrKVList = this.searchMfrKVList();
			String mfrNm = prdBscInfoVO.getMfrNm();
			if(null!=mfrNm){
				String val = (String) mfrNm;
				String newVal = val.trim();	//去空格
				newVal = org.springframework.util.StringUtils.replace(newVal, "（", "(");
				newVal = org.springframework.util.StringUtils.replace(newVal, "）", ")");
				if(CollectionUtils.isNotEmpty(mfrKVList)){
					for (KeyValueVO kv : mfrKVList) {
						if(kv.getValue().equals(newVal)){
							prdBscInfoVO.setMfrId(Long.valueOf(kv.getKey()));
							prdBscInfoVO.setMfrNm(kv.getValue());
						}
					}
				}
			}*/
		}
		return list;
	}
	
	/**
	 * 把添加失败的产品数据导出到excel中上传到服务器
	 * 返回错误日志路径
	 */
	private String exportErrorDataExcel(List<PrdBscInfoVO> voList){
		ExportParams params = new ExportParams("添加失败的产品信息", "产品", ExcelType.XSSF);
        params.setColor(HSSFColor.BRIGHT_GREEN.index);//表头颜色
        params.setStyle(ExcelExportStylerBorderImpl.class);
		XSSFWorkbook workbook = (XSSFWorkbook)ExcelExportUtil.exportExcel(params,PrdBscInfoVO.class, voList);
		String path = SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH + ProductConstant.PRD_IMPORT_INFO_SAVE_DIR;
		path = path + System.currentTimeMillis() + ".xlsx";
        //String path="C:/ExportProductTest/BatchAddFaiedInfo.xlsx"; 
        FileOutputStream fos = null;
        try {
            fos=new FileOutputStream(path);
            workbook.write(fos);
            fos.flush();
        } catch (FileNotFoundException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
        } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
        }finally {
            try {
            	if(null!=fos){
            		fos.close();
            	}
            } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
            }
        }
        return path;
        //return SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH + path;
	}
	
	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	private List<KeyValueVO> getKvList(String grpCd){
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "getKvList", "获取字典项组"+grpCd+"失败.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组"+grpCd+"失败,系统错误.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}

	@Override
	public List<KeyValueVO> searchDrvTypList() throws BaseException {
		List<KeyValueVO> kvList = new ArrayList<KeyValueVO>();
		List<SysDictionaryDTO> list = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRD_TYP_CATEGORY);
		List<String> tCodeList = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(list)){
			for (SysDictionaryDTO sysDictionaryDTO : list) {
				if(!tCodeList.contains(sysDictionaryDTO.getCode())){
					tCodeList.add(sysDictionaryDTO.getCode());
				}
			}
		}
		SysCdMapDQueryCondition condition = new SysCdMapDQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		condition.setmTypCd("M0003");
		//condition.setsGrpCd("PRD9999");
		condition.setsCodeList(tCodeList);
		
		List<SysCdMapDVO> SysCdMapDVOList = this.searchSysCdMapDList(condition);
		if(CollectionUtils.isNotEmpty(SysCdMapDVOList)){
			List<String> markList = new ArrayList<String>();
			for (SysCdMapDVO sysCdMapDVO : SysCdMapDVOList) {
				if(!markList.contains(sysCdMapDVO.getTCode())){
					KeyValueVO kv = new KeyValueVO();
					kv.setKey(sysCdMapDVO.getTCode());
					kv.setValue(sysCdMapDVO.getTCodeNm());
					kvList.add(kv);
					markList.add(sysCdMapDVO.getTCode());
				}
			}
		}
		return kvList;
	}

	@Override
	public List<KeyValueVO> searchHpList() throws BaseException {
		return this.getKvList(DictionaryConstant.CODE_PRD_HP);
	}

	@Override
	public boolean modifyAudStsCd(Long id, String audStsCd, Date mdfTm,
			Long mdfUsrId) throws BaseException {
		if(StringUtils.isEmpty(id)||StringUtils.isEmpty(audStsCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.productApiService.modifyPrdBscInfoAudStsCd(id, audStsCd, mdfTm, mdfUsrId);
	}

	@Override
	public String exportProduct(PrdBscInfoQueryCondition condition) throws BaseException {
		//设置初始查看权限条件prdTypCdList
		List<String> prdTypCdList = this.getPrdTypCdListForInitList();
		if(CollectionUtils.isEmpty(prdTypCdList)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "没有符合要求的产品.");
		}
		condition.setPrdTypCdList(prdTypCdList);
		String exportProductPath = this.productApiService.exportProduct(condition, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		
		return exportProductPath;
	}
}
